//
//  SADatePickerView.m
//  saasRetail
//
//  Created by 黄志刚 on 2022/5/10.
//

#import "SADatePickerView.h"
#import "NSArray+HDsafe.h"
#import "HDDatePickerCell.h"

@interface SADatePickerView ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
// pickerview  创建
@property (nonatomic ,strong) UIView *toolsView;
@property (nonatomic ,strong) UIDatePicker *pickerView;

@property (nonatomic,copy) NSString *titleString;//地址选择框标题
/** 当前选中地址 */
@property (strong, nonatomic) NSString *selectedDateString;
//回调
@property (copy, nonatomic) NSString *selectedDate;

@property (nonatomic ,strong) UICollectionView *collectionViewY;
@property (nonatomic ,strong) UICollectionView *collectionViewM;
@property (nonatomic ,strong) UICollectionView *collectionViewD;

@property (nonatomic ,assign) NSInteger dateYRow;//记录选中的行数
@property (nonatomic ,assign) NSInteger dateMRow;
@property (nonatomic ,assign) NSInteger dateDRow;

@property (nonatomic ,assign) NSInteger dateYRow2;//记录滑动函数
@property (nonatomic ,assign) NSInteger dateMRow2;//
@property (nonatomic ,assign) NSInteger dateDRow2;//

@property (nonatomic ,strong) NSMutableArray *dateYMarr;
@property (nonatomic ,strong) NSMutableArray *dateMMarr;
@property (nonatomic ,assign) NSInteger dateNum;

@property (nonatomic ,assign) BOOL isY;
@property (nonatomic ,assign) BOOL isM;
@property (nonatomic ,assign) BOOL isD;

@end

@implementation SADatePickerView

- (instancetype)initWithSlectedDate:(NSString *)selectedDate {
    if (self = [super init]){
        self.selectedDate  = selectedDate;
        [self setupUI];
    }
    return self;
}

#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.collectionViewY == collectionView) {
        return self.dateYMarr.count;
    }else if (self.collectionViewM == collectionView) {
        return self.dateMMarr.count;
    }
    return self.dateNum + 2;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"HDDatePickerCell";
    HDDatePickerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    if (self.collectionViewY == collectionView) {
        NSString *yStr = self.dateYMarr[indexPath.row];
        if (yStr.length > 0) {
            cell.titleLab.text = [NSString stringWithFormat:@"%@年",yStr];
        }else {
            cell.titleLab.text = @"";
        }
        if (indexPath.row == self.dateYRow) {
            cell.titleLab.textColor = kBuleColor;
        }else {
            cell.titleLab.textColor = kBlackColor;
        }
    }else if (self.collectionViewM == collectionView) {
        NSString *yStr = self.dateMMarr[indexPath.row];
        if (yStr.length > 0) {
            cell.titleLab.text = [NSString stringWithFormat:@"    %@月",yStr];
        }else {
            cell.titleLab.text = @"";
        }
        if (indexPath.row == self.dateMRow) {
            cell.titleLab.textColor = kBuleColor;
        }else {
            cell.titleLab.textColor = kBlackColor;
        }
    }else {
        if (indexPath.row == 0 || indexPath.row == self.dateNum + 1) {
            cell.titleLab.text = @"";
        }else {
            cell.titleLab.text = [NSString stringWithFormat:@"    %02zd日",indexPath.row];
        }
        if (indexPath.row == self.dateDRow) {
            cell.titleLab.textColor = kBuleColor;
        }else {
            cell.titleLab.textColor = kBlackColor;
        }
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.collectionViewY == scrollView) {
        [self.collectionViewM setContentOffset:self.collectionViewM.contentOffset animated:NO];
        [self.collectionViewD setContentOffset:self.collectionViewD.contentOffset animated:NO];

        CGPoint pInView = [self.toolsView convertPoint:self.collectionViewY.center toView:self.collectionViewY];
        NSIndexPath *indexPathNow = [self.collectionViewY indexPathForItemAtPoint:pInView];
        self.dateYRow = indexPathNow.row;
        self.dateMRow2 = self.dateMRow - 1;
        if (self.dateMRow2 < 0) {
            self.dateMRow2 = 0;
        }
        self.dateDRow2 = self.dateDRow - 1;
        if (self.dateDRow2 < 0) {
            self.dateDRow2 = 0;
        }
        [self.collectionViewY reloadData];
        
    }else if (self.collectionViewM == scrollView) {
        [self.collectionViewD setContentOffset:self.collectionViewD.contentOffset animated:NO];
        [self.collectionViewY setContentOffset:self.collectionViewY.contentOffset animated:NO];
        CGPoint pInView = [self.toolsView convertPoint:self.collectionViewM.center toView:self.collectionViewM];
        NSIndexPath *indexPathNow = [self.collectionViewM indexPathForItemAtPoint:pInView];
        self.dateMRow = indexPathNow.row;
        self.dateYRow2 = self.dateYRow - 1;
        if (self.dateYRow2 < 0) {
            self.dateYRow2 = 0;
        }
        
        self.dateDRow2 = self.dateDRow - 1;
        if (self.dateDRow2 < 0) {
            self.dateDRow2 = 0;
        }
        [self.collectionViewM reloadData];
    }else {
        [self.collectionViewM setContentOffset:self.collectionViewM.contentOffset animated:NO];
        [self.collectionViewY setContentOffset:self.collectionViewY.contentOffset animated:NO];
        CGPoint pInView = [self.toolsView convertPoint:self.collectionViewD.center toView:self.collectionViewD];
        NSIndexPath *indexPathNow = [self.collectionViewD indexPathForItemAtPoint:pInView];
        self.dateDRow = indexPathNow.row;
        self.dateYRow2 = self.dateYRow - 1;
        if (self.dateYRow2 < 0) {
            self.dateYRow2 = 0;
        }
        self.dateMRow2 = self.dateMRow - 1;
        if (self.dateMRow2 < 0) {
            self.dateMRow2 = 0;
        }
        [self.collectionViewD reloadData];
    }
}

//主要代码
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    CGFloat y = targetContentOffset->y;
    y += kScaleNum(22);
    NSInteger row  = y/(kScaleNum(45));
    targetContentOffset->y = row * kScaleNum(45);
    if (self.collectionViewY == scrollView) {
        [self.collectionViewM setContentOffset:CGPointMake(0, self.dateMRow2 * kScaleNum(45)) animated:NO];
        [self.collectionViewD setContentOffset:CGPointMake(0, self.dateDRow2 * kScaleNum(45)) animated:NO];
    }else if (self.collectionViewM == scrollView) {
        [self.collectionViewY setContentOffset:CGPointMake(0, self.dateYRow2 * kScaleNum(45)) animated:NO];
        [self.collectionViewD setContentOffset:CGPointMake(0, self.dateDRow2 * kScaleNum(45)) animated:NO];
    }else {
        [self.collectionViewM setContentOffset:CGPointMake(0, self.dateMRow2 * kScaleNum(45)) animated:NO];
        [self.collectionViewY setContentOffset:CGPointMake(0, self.dateYRow2 * kScaleNum(45)) animated:NO];
    }
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.collectionViewY == scrollView || self.collectionViewM == scrollView) {
        self.dateNum = [self getDaysWithYear:self.dateYMarr[self.dateYRow] month:self.dateMMarr[self.dateMRow]];
        [self.collectionViewD reloadData];
        if (self.dateDRow > self.dateNum - 1) {
            self.dateDRow = self.dateNum - 1;
            [self.collectionViewD setContentOffset:CGPointMake(0, self.dateDRow * kScaleNum(45)) animated:NO];
            CGPoint pInView = [self.toolsView convertPoint:self.collectionViewD.center toView:self.collectionViewD];
            NSIndexPath *indexPathNow = [self.collectionViewD indexPathForItemAtPoint:pInView];
            self.dateDRow = indexPathNow.row;
            [self.collectionViewD reloadData];
        }
    }
}

- (NSInteger)getDaysWithYear:(NSString *)yearStr
                       month:(NSString *)monthStr
{
    NSInteger year = [yearStr integerValue];
    NSInteger month = [monthStr integerValue];
    switch (month) {
        case 1:
            return 31;
            break;
        case 2:
            if (year%400==0 || (year%100!=0 && year%4 == 0)) {
                return 29;
            }else{
                return 28;
            }
            break;
        case 3:
            return 31;
            break;
        case 4:
            return 30;
            break;
        case 5:
            return 31;
            break;
        case 6:
            return 30;
            break;
        case 7:
            return 31;
            break;
        case 8:
            return 31;
            break;
        case 9:
            return 30;
            break;
        case 10:
            return 31;
            break;
        case 11:
            return 30;
            break;
        case 12:
            return 31;
            break;
        default:
            return 0;
            break;
    }
}

#pragma mark FlowLayoutDelegate
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
//    return CGSizeMake(itemWidth, self.height-20);
//}

#pragma mark - Private Methods
- (void)setupUI{
    
    self.dateYRow = 1;
    self.dateMRow = 1;
    self.dateDRow = 1;
    
    if (self.selectedDate.length == 0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd";
        NSString *dateStr = [formatter  stringFromDate:[NSDate date]];
        self.selectedDate = dateStr;
    }
    
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.backgroundColor =colorHexA(0x000000, 0.0);
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    }];
    
    _toolsView = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth - kScaleNum(289))/2, (kScreenHeight - kScaleNum(224))/2, kScaleNum(289), kScaleNum(224))];
    _toolsView.backgroundColor = [UIColor whiteColor];
    _toolsView.layer.cornerRadius = 3;
    _toolsView.layer.masksToBounds = YES;
    _toolsView.userInteractionEnabled = YES;
    [self addSubview:_toolsView];
    
    // 中间显示  label
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:SARectMake(0, 0, 289, 40)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"选择日期";
    titleLabel.font = kBFont(16);
    titleLabel.textColor = kBlackColor;
    [_toolsView addSubview:titleLabel];
    
    UIButton *cancelCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelCodeBtn.frame = CGRectMake(kScaleNum(0),kScaleNum(180), kScaleNum(144), kScaleNum(44));
    cancelCodeBtn.titleLabel.font = kFont(15);
    [cancelCodeBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelCodeBtn setTitleColor:kGrayColor forState:UIControlStateNormal];
    [cancelCodeBtn addTarget:self action:@selector(leftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_toolsView addSubview:cancelCodeBtn];
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmBtn.frame = CGRectMake(kScaleNum(145),kScaleNum(180), kScaleNum(144), kScaleNum(44));
    confirmBtn.titleLabel.font = kFont(15);
    [confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_toolsView addSubview:confirmBtn];
    
    UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, 40, 289, 1)];
    line.backgroundColor = kLineColor;
    [_toolsView addSubview:line];
    
    UIView *line2 = [[UIView alloc] initWithFrame:SARectMake(0, 180, 289, 1)];
    line2.backgroundColor = kLineColor;
    [_toolsView addSubview:line2];
    
    UIView *line3 = [[UIView alloc] initWithFrame:SARectMake(144, 180, 1, 44)];
    line3.backgroundColor = kLineColor;
    [_toolsView addSubview:line3];
    
//    // 左边取消按钮
//    UIButton *leftCancleButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    leftCancleButton.frame = CGRectMake(0, 0, 60, 44);
//    [leftCancleButton setTitle:@"取消" forState:UIControlStateNormal];
//    [leftCancleButton setTitleColor:colorHex(0xA5AEB7) forState:UIControlStateNormal];
//    leftCancleButton.titleLabel.font = kFont(15);
//    [leftCancleButton addTarget:self action:@selector(leftButtonClick:) forControlEvents:UIControlEventTouchUpInside];
//    [_toolsView addSubview:leftCancleButton];
    
    //    // 右边确定按钮
    //    UIButton *rightSureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    //    rightSureBtn.frame = SARectMake(kBaseScreenWidth - 60, 0, 60, 44);
    //    [rightSureBtn setTitle:@"确定" forState:UIControlStateNormal];
    //    rightSureBtn.titleLabel.font = kFont(15);
    //    [rightSureBtn setTitleColor:colorHex(0x3B9BFF) forState:UIControlStateNormal];
    //    [rightSureBtn addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [_toolsView addSubview:rightSureBtn];
    
    self.dateNum = 31;
    
    [_toolsView addSubview:self.collectionViewY];
    [_toolsView addSubview:self.collectionViewM];
    [_toolsView addSubview:self.collectionViewD];
    
    NSArray *dateArr = [self.selectedDate componentsSeparatedByString:@"-"];
    NSInteger y = 0;
    NSInteger m = 1;
    NSInteger d = 2;
    if (dateArr.count == 3) {
        y = [self.dateYMarr indexOfObject:dateArr[0]] - 1;
        m = [dateArr[1] integerValue] - 1;
        d = [dateArr[2] integerValue] - 1;
    }
    
    [self.collectionViewY setContentOffset:CGPointMake(0, y * kScaleNum(45)) animated:NO];
    [self.collectionViewM setContentOffset:CGPointMake(0, m * kScaleNum(45)) animated:NO];
    [self.collectionViewD setContentOffset:CGPointMake(0, d * kScaleNum(45)) animated:NO];
    
    UIView *blueView = [[UIView alloc] initWithFrame:SARectMake(30, 86, 229, 45)];
    blueView.layer.borderWidth = kScaleNum(1);
    blueView.layer.borderColor = kBuleColor.CGColor;
    blueView.layer.cornerRadius = kScaleNum(22.5);
    blueView.layer.masksToBounds = YES;
    blueView.userInteractionEnabled = NO;
    [_toolsView addSubview:blueView];
    
    self.collectionViewD.hidden = YES;
}

//左边按钮(取消)
- (void)leftButtonClick:(UIButton *)button{
    [self dismiss];
}
//  右边按钮 (确认)
- (void)rightButtonClick:(UIButton *)button{
    [self.collectionViewY setContentOffset:self.collectionViewY.contentOffset animated:NO];
    [self.collectionViewM setContentOffset:self.collectionViewM.contentOffset animated:NO];
    [self.collectionViewD setContentOffset:self.collectionViewD.contentOffset animated:NO];
    CGPoint pInViewY = [self.toolsView convertPoint:self.collectionViewY.center toView:self.collectionViewY];
    NSIndexPath *indexPathNowY = [self.collectionViewY indexPathForItemAtPoint:pInViewY];
    CGPoint pInViewM = [self.toolsView convertPoint:self.collectionViewM.center toView:self.collectionViewM];
    NSIndexPath *indexPathNowM = [self.collectionViewM indexPathForItemAtPoint:pInViewM];
    CGPoint pInViewD = [self.toolsView convertPoint:self.collectionViewD.center toView:self.collectionViewD];
    NSIndexPath *indexPathNowD = [self.collectionViewD indexPathForItemAtPoint:pInViewD];
    self.selectedDate = [NSString stringWithFormat:@"%@-%@-%02zd",self.dateYMarr[indexPathNowY.row],self.dateMMarr[indexPathNowM.row],indexPathNowD.row];
    !self.selectDateBlock ?: self.selectDateBlock(self.selectedDate);
    [self dismiss];
}
//屏幕点击事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self dismiss];
}
- (void)show{
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
}
//消失的方法
- (void)dismiss{
    __weak typeof (self)weakSelf = self;
    __weak typeof(UIView *)blockView = _toolsView;
    __weak typeof(UIDatePicker *)blockPickerViwe = _pickerView;
    [UIView animateWithDuration:0.3 animations:^{
        blockView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScaleNum(44));
        blockPickerViwe.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScaleNum(200));
    }completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
    }];
}

//-(void)layoutSubviews {
//
//    [self.collectionViewY scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:9 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
//}

#pragma mark - Getter or Setter
-(UICollectionView *)collectionViewY {
    if (!_collectionViewY) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake(kScaleNum(69), kScaleNum(45));
        flow.minimumInteritemSpacing = 0.000001f;
        flow.minimumLineSpacing = 0.000001f;
        _collectionViewY = [[UICollectionView alloc]initWithFrame:CGRectMake(kScaleNum(71), kScaleNum(41), kScaleNum(69), kScaleNum(135)) collectionViewLayout:flow];
        _collectionViewY.backgroundColor = [UIColor clearColor];
        _collectionViewY.dataSource = self;
        _collectionViewY.delegate = self;
        _collectionViewY.showsVerticalScrollIndicator = NO;
        _collectionViewY.showsHorizontalScrollIndicator = NO;
//        _collectionViewY.pagingEnabled = YES;
        _collectionViewY.bounces = NO;
        [_collectionViewY registerClass:[HDDatePickerCell class] forCellWithReuseIdentifier:@"HDDatePickerCell"];
    }
    return _collectionViewY;
}

-(UICollectionView *)collectionViewM {
    if (!_collectionViewM) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake(kScaleNum(69), kScaleNum(45));
        flow.minimumInteritemSpacing = 0.000001f;
        flow.minimumLineSpacing = 0.000001f;
        _collectionViewM = [[UICollectionView alloc]initWithFrame:CGRectMake(kScaleNum(149), kScaleNum(41), kScaleNum(69), kScaleNum(135)) collectionViewLayout:flow];
        _collectionViewM.backgroundColor = [UIColor clearColor];
        _collectionViewM.dataSource = self;
        _collectionViewM.delegate = self;
        _collectionViewM.showsVerticalScrollIndicator = NO;
        _collectionViewM.showsHorizontalScrollIndicator = NO;
//        _collectionViewY.pagingEnabled = YES;
        _collectionViewM.bounces = NO;
        [_collectionViewM registerClass:[HDDatePickerCell class] forCellWithReuseIdentifier:@"HDDatePickerCell"];
    }
    return _collectionViewM;
}

-(UICollectionView *)collectionViewD {
    if (!_collectionViewD) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.itemSize = CGSizeMake(kScaleNum(69), kScaleNum(45));
        flow.minimumInteritemSpacing = 0.000001f;
        flow.minimumLineSpacing = 0.000001f;
        _collectionViewD = [[UICollectionView alloc]initWithFrame:CGRectMake(kScaleNum(149), kScaleNum(41), kScaleNum(69), kScaleNum(135)) collectionViewLayout:flow];
        _collectionViewD.backgroundColor = [UIColor clearColor];
        _collectionViewD.dataSource = self;
        _collectionViewD.delegate = self;
        _collectionViewD.showsVerticalScrollIndicator = NO;
        _collectionViewD.showsHorizontalScrollIndicator = NO;
//        _collectionViewY.pagingEnabled = YES;
        _collectionViewD.bounces = NO;
        [_collectionViewD registerClass:[HDDatePickerCell class] forCellWithReuseIdentifier:@"HDDatePickerCell"];
    }
    return _collectionViewD;
}

-(NSMutableArray *)dateYMarr {
    if (!_dateYMarr) {
        _dateYMarr = [NSMutableArray array];
        [_dateYMarr addObject:@""];
        for (NSInteger i = 0; i < 200; i++) {
            [_dateYMarr addObject:[NSString stringWithFormat:@"%zd",1921 + i]];
        }
        [_dateYMarr addObject:@""];
    }
    return _dateYMarr;
}

-(NSMutableArray *)dateMMarr {
    if (!_dateMMarr) {
        _dateMMarr = [NSMutableArray array];
        [_dateMMarr addObject:@""];
        for (NSInteger i = 0; i < 12; i++) {
            [_dateMMarr addObject:[NSString stringWithFormat:@"%02zd", i + 1]];
        }
        [_dateMMarr addObject:@""];
    }
    return _dateMMarr;
}

@end
